# coding:utf-8
import os
import urllib
import json

from sqlalchemy import event

from ..constant import Choice
from ..extensions import im_sync_proxy, user_sync_proxy
from common.utils import redis_client
from common.im_util import IM_LIST_REDIS_KEY
from .models import User, CancelAttentionUser, UserTag, UserInfo, \
    Follow
from app.relationship.models import MobileList


@event.listens_for(User, 'after_insert')
def user_set_im_token(mapper, connection, target):
    """
    created by chenhj at 2017/8/22
    为用户分配IM, 同时同步用户的手机归属地/战区信息
    """
    im_token_cache = redis_client.zrangebyscore(IM_LIST_REDIS_KEY, target.id, target.id)
    if im_token_cache:
        im_token = im_token_cache[0]
        if isinstance(im_token, bytes):
            im_token = im_token.decode('utf8')
        connection.execute(
            User.__table__.update().values(
                im_token=str(im_token),
            ).where(
                User.__table__.c.id == target.id
            )
        )
        redis_client.zremrangebyscore(IM_LIST_REDIS_KEY, target.id, target.id)
        user_sync_proxy.send(json.dumps({
            'user_id': target.id,
            'mobile': target.mobile
        }))

    # 写入标签信息
    connection.execute(
        UserTag.__table__.insert().values(
            user_id=target.id,
            follow_state=0,
            aspiration=0,
            gold_aspiration=0,
            supplier_aspiration=0,
            pay_aspiration=0,
            paid_feel=0,
            mastery=0,
            scale=0,
            contact_frequency=0,
            injured=0,
            few_order=False,
            small_order=False,
            fake_order=False,
            crowd_order=False,
            unfair_rule=False,
            install=True,
            repair=True,
            rent=True
        )
    )

    # 写入user_info
    connection.execute(
        UserInfo.__table__.insert().values(
            user_id=target.id,
            com_summary=''
        )
    )


@event.listens_for(User.avatar, 'set', active_history=True)
def sync_user_avatar_to_im(target, value, oldvalue, initiator):
    """
    created by chenhj at 2017/8/23

    """
    if oldvalue != value:
        host = os.environ.get('img_host')
        im_sync_proxy.send(json.dumps(dict(
            func='update_user_info',
            kwargs={
                'accid': target.id,
                'icon': urllib.parse.urljoin(host, value),
                'com': target.com,
                'city': target.city,
                'type': target.type
            }
        )))


@event.listens_for(User.mobile, 'set', active_history=True)
def sync_mobile_list_mobile(target, value, oldvalue, initiator):
    """
    create by ld_wu 2018-01-08
    更新用户通讯录的电话信息
    """
    if oldvalue != value:
        if oldvalue:
            MobileList.update_mobile(target.id, value)


@event.listens_for(User.nickname, 'set', active_history=True)
def sync_user_nickname_to_im(target, value, oldvalue, initiator):
    """
    created by chenhj at 2017/8/23

    """
    if oldvalue != value:
        im_sync_proxy.send(json.dumps(dict(
            func='update_user_info',
            kwargs={
                'accid': target.id,
                'name': value,
                'com': target.com,
                'city': target.city,
                'type': target.type
            }
        )))
        follows = Follow.query.filter(
            Follow.follower_id == target.id,
            Follow.has_set_alias.__eq__(False)
        ).all()

        for each in follows:
            each.alias = value


@event.listens_for(User.com, 'set', active_history=True)
def sync_user_com_to_im(target, value, oldvalue, initiator):
    """
    created by chenhj at 2017/8/23

    """
    if oldvalue != value:
        to_send_data = {
            'accid': target.id,
            'com': value,
            'city': target.city,
            'type': target.type
        }
        im_sync_proxy.send(json.dumps(dict(
            func='update_user_info',
            kwargs=to_send_data
        )))


@event.listens_for(User.city, 'set', active_history=True)
def sync_user_city_to_im(target, value, oldvalue, initiator):
    """
    created by chenhj at 2017/8/23

    """
    if oldvalue != value:
        to_send_data = {
            'accid': target.id,
            'city': value,
            'com': target.com,
            'type': target.type,
        }
        im_sync_proxy.send(json.dumps(dict(
            func='update_user_info',
            kwargs=to_send_data
        )))


@event.listens_for(User.type, 'set', active_history=True)
def sync_user_type_to_im(target, value, oldvalue, initiator):
    """
    created by chenhj at 2017/8/23

    """
    if oldvalue != value:
        to_send_data = {
            'accid': target.id,
            'type': value,
            'com': target.com,
            'city': target.city,
        }
        im_sync_proxy.send(json.dumps(dict(
            func='update_user_info',
            kwargs=to_send_data
        )))


@event.listens_for(User.wx_openid, 'set', active_history=True)
def sync_cancel_attention_users_records(target, value, oldvalue, initiator):
    """
    add by zhouhl 2017-09-11
    同步取关用户记录的当前关注状态
    """
    if oldvalue != value:
        new_current_attention = Choice.NO.value if value=='' \
            else Choice.YES.value
        update_records = CancelAttentionUser.query.filter_by(uid=target.id)
        for i in update_records:
            i.current_attention = new_current_attention
